package com.stnet.web.enterprice.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.modules.commons.PageAction;
import com.opensymphony.xwork2.ActionContext;
import com.stnet.bases.BaseAction;
import com.stnet.entity.Users;
import com.stnet.entity.WxProjectOrder;
import com.stnet.entity.WxSendContent;
import com.stnet.service.enterprice.system.AuthOrderManagerDao;
import com.stnet.service.enterprice.system.WxSendContentManagerDao;
import com.weihao.sd.utils.AccessToken;
import com.weihao.sd.utils.MessageUtil;
import com.weihao.sd.utils.SmsClientUtils;
import com.weihao.sd.utils.SmsDto;
import com.weihao.sd.utils.TokenThread;
import com.weihao.sd.utils.WxClientUtils;

public class AuthOrderAction extends PageAction {
	
	private WxProjectOrder order;
	
	private WxSendContent wsc;
	
	private List<WxProjectOrder> wxProjectOrderList;
	
	private String receiver;
	
	private String code;
	
	private Map data;
	
	private String wxUrl;
	
	private String smsUrl;
	
	private String account;
	
	private String pswd;
	
	private String appid;

	private String appSecret;
	
	private AuthOrderManagerDao authOrderManagerDao;
	
	private WxSendContentManagerDao wxSendContentManagerDao;

	private static Logger logger = LoggerFactory
			.getLogger(AuthOrderAction.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = -6321682932023949985L;

	public String execute() throws Exception {
		clearMessages();
		HttpServletRequest request = ServletActionContext.getRequest();
		String code = request.getParameter("code");
		logger.warn("获取code：：" + code);
		StringBuffer s = new StringBuffer();
		s.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
		s.append(appid);
		s.append("&secret=");
		s.append(appSecret);
		s.append("&code=");
		s.append(code);
		s.append("&grant_type=authorization_code");

		String url = s.toString();
//		logger.warn("请求url为：" + url);

		JSONObject wx = WxClientUtils.getWx(url);
		if (!wx.has(WxClientUtils.ERROR_CODE)) {
			String accessToken = wx.getString("access_token");
			String openId = wx.getString("openid");
			request.getSession().setAttribute("openId", openId);
//			request.getSession().setAttribute("access_token", accessToken);
			logger.warn("获取的accessToken成功");
			return "toadd";
		}
		else{
			logger.warn("请求错误：" +wx.getString(WxClientUtils.ERROR_MSG));
		}
		

		return renderText(code);
	}
	
	public String delete(){
		
//		clearMessages();
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		authOrderManagerDao.deleteAuthOrder(Long.valueOf(id));
		
		
		return this.list();
	}
	
	public String view(){
		
//		clearMessages();
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		String toView = request.getParameter("toView");
		order = authOrderManagerDao.getAuthOrder(Long.valueOf(id));
		String proType = order.getProType();
		if(null != proType && !"".equals(proType)){
			String[] split = proType.split(",");
			order.setTypes(split);
		}
		if("tosend".equals(toView)){
			return "tosend";
		}
		if("toedit".equals(toView)){
			return "toedit";
		}
		return "view";
	}
	
	public String list(){
		super.pager = authOrderManagerDao.findAuthOrderByPage(pageSize, pageNo);
		
		wxProjectOrderList = super.pager.getResultList();
		for(int i=0;i<wxProjectOrderList.size();i++){
			WxProjectOrder wxProjectOrder = wxProjectOrderList.get(i);
			String proType = wxProjectOrder.getProType();
			if(null != proType && !"".equals(proType)){
				String[] split = proType.split(",");
				wxProjectOrder.setTypes(split);
			}
		}
		
		return "list";
	}
	
	//微信、后台共用一个跳转（jax.xml；mobile.xml)
	public String initAdd(){
		return "toadd";
	}
	
	public String add(){
		Users users = null;
		Map session = (Map) ActionContext.getContext().getSession();
		if (session.get("users") != null)
			users = (Users) session.get("users");
		
		String[] types = order.getTypes();
		if(null!=types && types.length>0){
			StringBuffer b = new StringBuffer();
			for(String type:types){
				if(!"".equals(type)){
					b.append(type);
					b.append(",");
				}
			}
			order.setProType(b.substring(0, b.length()-1));
			logger.warn("项目类型为："+order.getProType());
		}
		order.setOderDate(new Date());
		order.setOpDate(new Date());
		order.setOpId(users.getLoginName());
		authOrderManagerDao.addAuthOrder(order);
		return this.list();
	}
	
	public String wxadd(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String openId = (String) request.getSession().getAttribute("openId");
		
		if("".equals(openId)){
			logger.error("微信OpenID不存在！！");
			addActionError("微信OpenID不存在！！");
			return renderText("<h1>提交出错，请先绑定会员账号！</h1>");
		}
		
		String[] types = order.getTypes();
		if(null!=types && types.length>0){
			StringBuffer b = new StringBuffer();
			for(String type:types){
				if(!"".equals(type)){
					b.append(type);
					b.append(",");
				}
			}
			if(b.length()>=1)
				order.setProType(b.substring(0, b.length()-1));
			logger.warn("项目类型为："+order.getProType());
		}
		order.setOpenId(openId);
		order.setOderDate(new Date());
		authOrderManagerDao.addAuthOrder(order);
		return renderText("<h1>提交完成，谢谢！</h1>");
	}
	
	public String update(){
		Users users = null;
		Map session = (Map) ActionContext.getContext().getSession();
		if (session.get("users") != null)
			users = (Users) session.get("users");
		WxProjectOrder owpo = authOrderManagerDao.getAuthOrder(order.getId());
		
		String[] types = order.getTypes();
		if(null!=types && types.length>0){
			StringBuffer b = new StringBuffer();
			for(String type:types){
				if(!"".equals(type)){
					b.append(type);
					b.append(",");
				}
			}
			owpo.setProType(b.substring(0, b.length()-1));
			logger.warn("项目类型为："+owpo.getProType());
		}
		else
			owpo.setProType(null);
		owpo.setProDesc(order.getProDesc());
		owpo.setName(order.getName());
		owpo.setOpDate(new Date());
		owpo.setOpId(users.getLoginName());
		authOrderManagerDao.updateAuthOrder(owpo);
		return this.list();
	}
	
	public String sendSmsCode(){
		data = new HashMap();
		
		if("".equals(receiver)){
			logger.error("请输入手机！！");
			data.put("json", "请输入手机");
			return SUCCESS;
		}
		
		logger.warn("接收ID为："+receiver);
		logger.warn("smsUrl为："+smsUrl);
		try {
			SmsDto smsDto = new SmsDto();
			String ocode = MessageUtil.getCode(4);
			String content = "本次提交的验证码为："+ocode+" 请注意保密！";
			smsDto.setAccount(account);
			smsDto.setPswd(pswd);
			smsDto.setContent(content);
			smsDto.setMobiles(receiver);
			smsDto.setNeedstatus(false);
			logger.warn("发送消息："+content);
			JSONObject wx = SmsClientUtils.postSms(smsUrl, smsDto);
//			JSONObject wx = new JSONObject();
//			wx.put(SmsClientUtils.ERROR_CODE, "0");
			if(!wx.has(SmsClientUtils.ERROR_CODE)){
				String respstatus = wx.getString("respstatus");
				if("0".equals(respstatus)){
					ActionContext.getContext().getSession().put(receiver, ocode);
					data.put("json", "发送成功");
				}
			}
			else{
				String msg = wx.getString(SmsClientUtils.ERROR_MSG);
				data.put("json", msg);
				logger.warn(msg);
			}
			
		} catch (JSONException e) {
			logger.error("调用失败！",e);
			data.put("json", "发送失败");
		}
		
		return SUCCESS;
	}
	
	public String sendMsg(){
		
		if("".equals(wsc.getToUser())){
			logger.error("微信OpenID不存在！！");
			addActionError("微信OpenID不存在！！");
			return ERROR;
		}
		
		
		AccessToken accessToken = TokenThread.accessToken;
		if(null == accessToken || "".equals(accessToken.getToken())){
			logger.error("accessToken获取失败！！");
			addActionError("微信OpenID不存在！！");
			return ERROR;
		}
		Users users = null;
		Map session = (Map) ActionContext.getContext().getSession();
		if (session.get("users") != null)
			users = (Users) session.get("users");
		
		String token = accessToken.getToken();
		String sendUrl = wxUrl+token;
		
		logger.warn("接收ID为："+receiver);
		logger.warn("sendurl为："+sendUrl);
		try {
			JSONObject tm = new JSONObject();
			tm.put("touser", wsc.getToUser());
			tm.put("msgtype", MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			JSONObject text = new JSONObject();
			String content = wsc.getToText();
			if(null == content || "".equals(content)){
				logger.error("发送内容不能为空！！");
				addActionError("发送内容不能为空！！");
				return ERROR;
			}
			text.put("content", content);
			tm.put("text", text);
			String json = tm.toString();
			logger.warn("推送消息："+json);
			
			JSONObject wx = WxClientUtils.postWx(sendUrl, json);
			if (0 == wx.getInt(WxClientUtils.ERROR_CODE)) {
				logger.warn("消息发送成功!");
				wsc.setsDate(new Date());
				wsc.setOpId(users.getLoginName());
				wxSendContentManagerDao.addWxSendContent(wsc);
				return this.list();
			}
			else{
				addActionError("消息发送失败!");
				String msg = wx.getString(WxClientUtils.ERROR_MSG);
				logger.warn(msg);
			}
			
		} catch (JSONException e) {
			logger.error("调用失败！",e);
			addActionError("消息发送异常!");
		}
		return ERROR;
		
	}

	public String checkCode(){
		logger.warn("手机："+receiver+"验证码: "+code);
		String ocode = (String) ActionContext.getContext().getSession().get(receiver);
		if(code.equals(ocode)){
			logger.warn("验证成功："+ocode);
			return renderText("true");
		}
		logger.warn("验证失败："+ocode);
		System.out.println("shibai!!!");
		return renderText("false");
	}
	
	

	public void setWxSendContentManagerDao(
			WxSendContentManagerDao wxSendContentManagerDao) {
		this.wxSendContentManagerDao = wxSendContentManagerDao;
	}

	public WxSendContent getWsc() {
		return wsc;
	}

	public void setWsc(WxSendContent wsc) {
		this.wsc = wsc;
	}

	public List<WxProjectOrder> getWxProjectOrderList() {
		return wxProjectOrderList;
	}

	public void setWxProjectOrderList(List<WxProjectOrder> wxProjectOrderList) {
		this.wxProjectOrderList = wxProjectOrderList;
	}
	
	

	public void setAuthOrderManagerDao(AuthOrderManagerDao authOrderManagerDao) {
		this.authOrderManagerDao = authOrderManagerDao;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Map getData() {
		return data;
	}

	public void setData(Map data) {
		this.data = data;
	}

	public String getReceiver() {
		return receiver;
	}

	public void setReceiver(String receiver) {
		this.receiver = receiver;
	}

	public WxProjectOrder getOrder() {
		return order;
	}

	public void setOrder(WxProjectOrder order) {
		this.order = order;
	}
	
	public void setWxUrl(String wxUrl) {
		this.wxUrl = wxUrl;
	}

	public void setSmsUrl(String smsUrl) {
		this.smsUrl = smsUrl;
	}
	
	public void setAccount(String account) {
		this.account = account;
	}

	public void setPswd(String pswd) {
		this.pswd = pswd;
	}

	public String getAppid() {
		return appid;
	}

	public void setAppid(String appid) {
		this.appid = appid;
	}

	public String getAppSecret() {
		return appSecret;
	}

	public void setAppSecret(String appSecret) {
		this.appSecret = appSecret;
	}

}
